const PROXY_TARGET = 'https://ai.yinlimedia.com';

// 处理代理请求
async function handleRequest(request) {
  const url = new URL(request.url);
  const targetUrl = PROXY_TARGET + url.pathname + url.search;

  // 复制原始请求头
  const headers = new Headers(request.headers);
  headers.set('Origin', PROXY_TARGET);
  
  try {
    const response = await fetch(targetUrl, {
      method: request.method,
      headers: headers,
      body: request.body,
      credentials: 'include'
    });

    // 创建新的响应头
    const responseHeaders = new Headers(response.headers);
    responseHeaders.set('Access-Control-Allow-Origin', '*');
    responseHeaders.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    responseHeaders.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');

    return new Response(response.body, {
      status: response.status,
      statusText: response.statusText,
      headers: responseHeaders
    });
  } catch (error) {
    return new Response(JSON.stringify({ error: error.message }), {
      status: 500,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
      }
    });
  }
}

// 监听请求
self.addEventListener('fetch', event => {
  if (event.request.url.includes('/proxy/')) {
    event.respondWith(handleRequest(event.request));
  }
}); 